package com.epam.tcs.actions.pages;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.ObjectNotFoundException;

import com.epam.tcs.actions.BreadCrumb;
import com.epam.tcs.dao.factory.DAO;
import com.epam.tcs.dao.hibernate.entities.Lecture;
import com.epam.tcs.dao.hibernate.entities.Theme;

public class LecturePage extends PageAbstract {

	@Override
	public void doExec(HttpServletRequest req, HttpServletResponse res) {

		String target = req.getRequestURI().substring(
				req.getContextPath().length());

		String[] tarr = target.split("/");

		BreadCrumb.add(req, res, "Лекции", "/tcs/lecture");
		try {
			if ((tarr.length == 4) && tarr[3].equals("add")) {
				addLecture(req, res);
			} else if ((tarr.length == 4) && tarr[3].equals("del")) {
				delLecture(req, res);
			} else if ((tarr.length == 4) && tarr[3].equals("edit")) {
				editLecture(req, res);
			} else if ((tarr.length == 4) && tarr[3].equals("show")) {
				showLecture(req, res);
			} else {
				listLectures(req, res);
			}
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void showLecture(HttpServletRequest req, HttpServletResponse res)
			throws IOException, ServletException {
		DAO<Lecture> lecture = dao.getLectureDAO();
		if (req.getParameter("lecture_id") != null) {
			Lecture l = lecture.getElement(Long.parseLong(req
					.getParameter("lecture_id")));
			req.getSession().setAttribute("lecture", l);
			BreadCrumb.add(req, res, "Лекция \"" + l.getName() + "\"",
					"/tcs/lecture/show?lecture_id=" + l.getLecPracId());
		}

		outputPage("lecture/lecture_show.jsp", req, res);
	}

	private void listLectures(HttpServletRequest req, HttpServletResponse res)
			throws IOException, ServletException {
		DAO<Lecture> lecture = dao.getLectureDAO();
		req.setAttribute("widget", "lecture");
		req.getSession().setAttribute("listLectures", lecture.getAllElements());
		outputPage("lecture/lecture.jsp", req, res);
	}

	private void addLecture(HttpServletRequest req, HttpServletResponse res)
			throws IOException, ServletException {
		BreadCrumb.add(req, res, "Добавить лекцию", "/tcs/lecture/add");
		DAO<Lecture> lecture = dao.getLectureDAO();
		DAO<Theme> theme = dao.getThemeDAO();
		if (req.getMethod() == "POST" && this.validateLectureForm(req)) {
			Lecture l = new Lecture();
			l.setName(req.getParameter("caption"));
			l.setTheme(theme.getElement(Integer.parseInt(req
					.getParameter("theme"))));
			l.setDescription(req.getParameter("description"));

			if (lecture.addElement(l) != 0L) {
				req.setAttribute("message", "Лекция \"" + l.getName()
						+ "\" успешно добавлена.");
			}
		}
		req.getSession().setAttribute("listThemes", theme.getAllElements());
		req.setAttribute("widget", "add_lecture");
		req.setAttribute("action", "/tcs/lecture/add");
		outputPage("lecture/lecture_form.jsp", req, res);
	}

	private void editLecture(HttpServletRequest req, HttpServletResponse res)
			throws IOException, ServletException {
		if (req.getParameter("lecture_id") != null
				&& Long.parseLong(req.getParameter("lecture_id")) > 0) {
			DAO<Lecture> lecture = dao.getLectureDAO();
			try {
				Lecture l = lecture.getElement(Integer.parseInt(req
						.getParameter("lecture_id")));
				BreadCrumb.add(req, res, "Изменить лекцию " + l.getName(),
						"/tcs/lecture/edit?lecture_id=" + l.getLecPracId());
				DAO<Theme> theme = dao.getThemeDAO();
				if (req.getMethod() == "POST" && this.validateLectureForm(req)) {
					l.setTheme(theme.getElement(Integer.parseInt(req
							.getParameter("theme"))));
					l.setName(req.getParameter("caption"));
					l.setDescription(req.getParameter("description"));

					try {
						lecture.updateElement(l);
						req.setAttribute("message", "Лекция \"" + l.getName()
								+ "\" изменена.");
					} catch (Exception e) {
						req.setAttribute("message",
								"Попытка изменить лекцию вызвала исключение: "
										+ e.getMessage());
					}
				}
				req.setAttribute("widget", "edit_lecture");
				req.setAttribute("action",
						"/tcs/lecture/edit?lecture_id=" + l.getLecPracId());
				req.setAttribute("lecture", l);
				req.getSession().setAttribute("listThemes",
						theme.getAllElements());
				outputPage("lecture/lecture_form.jsp", req, res);

			} catch (ObjectNotFoundException e) {
				res.sendRedirect(req.getContextPath() + "/tcs/lecture/add");
			}
		}
	}

	private void delLecture(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		DAO<Lecture> lecture = dao.getLectureDAO();
		ArrayList<String> lectures_name = new ArrayList<String>();
		for (Enumeration<String> e = req.getParameterNames(); e
				.hasMoreElements();) {
			String[] s = ((String) e.nextElement()).split("_");
			Lecture lecture_element = (Lecture) lecture.getElement(Integer
					.parseInt(s[2]));
			lectures_name.add(lecture_element.getName());
			lecture.deleteElement(lecture.getElement(Integer.parseInt(s[2])));
		}
		req.setAttribute("widget", "lecture");
		req.setAttribute("message",
				"Удалены лекции: " + lectures_name.toString());
		req.getSession().setAttribute("listLectures", lecture.getAllElements());
		outputPage("lecture/lecture.jsp", req, res);
	}

	private boolean validateLectureForm(HttpServletRequest req) {
		// TODO Auto-generated method stub
		return true;
	}

}
